<?php

namespace app\api\controller\mycurrency;

use addons\mycurrency\library\Common;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\mycurrency\OperateDistributionConfig;
use app\common\model\mycurrency\OperateDistributionMoneylog;
use app\common\model\mycurrency\OperateDistributionMoneyWithdrawal;
use app\common\model\mycurrency\OperateDistributionProfit;
use app\common\model\mycurrency\OperateDistributionUser;
use app\common\model\mycurrency\OperateDistributionUserApplyfor;
use fast\Random;
use think\Config;
use think\Exception;
use think\Validate;
use think\Db;

/**
 * 营销 - 分销接口
 */
class OperateDistribution extends Api
{
    protected $noNeedLogin = ['distributionConfig','test'];
    protected $noNeedRight = '*';
    protected $distribution_user = null;

    protected $verificationIdentity = ['distributionConfig','distributionApplyfor','test'];//不验证是否是分销员

    public function _initialize()
    {
        parent::_initialize();

        if (!$this->auth->match($this->verificationIdentity)) {
            $distribution_user = OperateDistributionUser::where(['user_id' => $this->auth->id,'deletetime' => null])->find();
            if (!$distribution_user){
                $this->error('还不是分销员');
            }
            $this->distribution_user = $distribution_user;
        }
    }

    /**
     * 分销配置
    */
    public function distributionConfig(){
        $data = OperateDistributionConfig::get(1);
        $this->success('加载成功',$data);
    }

    /**
     * 分销员申请
    */
    public function distributionApplyfor(){
        $param = $this->request->param();
        $rule = [
            ['full_name', 'require', '分销员姓名不能为空'],
            ['mobile', 'require', '分销员电话'],
            ['explain', 'require', '用户申请说明'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $user_id = $this->auth->id;
        if (OperateDistributionUser::where(['user_id' => $user_id,'deletetime' => null])->find()){
            $this->error('已经是分销员，请勿重复申请');
        }
        if (OperateDistributionUserApplyfor::where(['user_id' => $user_id,'deletetime' => null,'status' => ['<>',OperateDistributionUserApplyfor::STATUS_BOHUEI]])->find()){
            $this->error('已提交审核，请勿重复提交');
        }
        $increase = [
            'user_id' => $user_id,
            'full_name' => $param['full_name'],
            'mobile' => $param['mobile'],
            'explain' => $param['explain'],
            'status' => OperateDistributionUserApplyfor::STATUS_DAISHENHE,
            'createtime' => time(),
            'avatar' => $param['avatar'],
        ];
        $res = OperateDistributionUserApplyfor::create($increase);
        if (!$res){
            $this->error('申请失败');
        }
        $this->success('申请成功');
    }

    /**
     * 分销员详情
     */
    public function distributionInfo(){
        $data = $this->distribution_user;
        $data['wechat_code_image_http'] = $data['wechat_code_image'] == null ? '' : Common::GetHost() . $data['wechat_code_image'];
        $data['alipay_code_image_http'] = $data['alipay_code_image'] == null ? '' : Common::GetHost() . $data['alipay_code_image'];
        //默认查询条件
        $where1 = $where2 = ['distribution_user_id' => $this->distribution_user->id,'deletetime' => null];
        $where1['status'] = OperateDistributionProfit::STATUS_YIFENCHENG;//已分成
        $where2['status'] = ['in',[OperateDistributionProfit::STATUS_WEIFENCHENG,OperateDistributionProfit::STATUS_FENCHENGZHONG,]];//待分成

        //今日时间戳
        $todayTime =  strtotime(date("Y-m-d 00:00:00")).','.strtotime(date("Y-m-d 23:59:59"));

        //本周开始 及本周 结束时间戳
        $startTimestamp = strtotime("this week Monday");
        $endTimestamp = strtotime("this week Sunday") + 86400 - 1;
        $circumTime = $startTimestamp.','.$endTimestamp;

        //本月开始 及本月 结束时间戳
        $firstDayOfMonth = strtotime(date('Y-m-01 00:00:00'));
        $lastDayOfMonth = strtotime(date('Y-m-t 23:59:59'));
        $themoonTime = $firstDayOfMonth . ',' . $lastDayOfMonth;

        $statistics = [
            'profit_total' => OperateDistributionProfit::where($where1)->sum('actual_income'),//总计收益
            'profit_canreflect' => $data['money'],//可提现收益
            'profit_today' => OperateDistributionProfit::where($where1)->where(['divideintotime' => ['between',$todayTime]])->sum('actual_income'),//今日收益
            'profit_thisweek' => OperateDistributionProfit::where($where1)->where(['divideintotime' => ['between',$circumTime]])->sum('actual_income'),//本周收益
            'profit_thismonth'=> OperateDistributionProfit::where($where1)->where(['divideintotime' => ['between',$themoonTime]])->sum('actual_income'),//本月收益
            'bdaboutto'=> OperateDistributionProfit::where($where2)->sum('actual_income'),//待分成收益
            'stop_withdrawal' => OperateDistributionMoneyWithdrawal::where([
                'distribution_user_id' => $this->distribution_user->id,
                'status' => ['in',[
                    OperateDistributionMoneyWithdrawal::STATUS_DAICHULI,
                    OperateDistributionMoneyWithdrawal::STATUS_SHENHETONGGUO,
                    OperateDistributionMoneyWithdrawal::STATUS_DAKUANZHONG,
                    OperateDistributionMoneyWithdrawal::STATUS_YIDAKUAN,
                ]],
                'deletetime' => null
            ])->sum('money'),//已提现收益 包括已提现 及提现中的
        ];

        $this->success('加载成功',[
            'info' => $data,
            'statistics' => $statistics,
        ]);
    }

    /**
     * 分销员信息修改
    */
    public function distributionUpdate(){
        $param = $this->request->param();
        $rule = [
            ['full_name', 'require', '分销员姓名不能为空'],
            ['mobile', 'require', '分销员电话'],
            ['avatar', 'require', '分销员头像不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $update = [
            'full_name' => $param['full_name'],
            'mobile' => $param['mobile'],
            'updatetime' => time(),
            'avatar' => $param['avatar'],
        ];
        $res = OperateDistributionUser::where(['id' => $this->distribution_user->id])->update($update);
        if (!$res){
            $this->error('修改失败');
        }
        $this->success('修改成功');
    }

    /**
     * 我的团队
     */
    public function distributionTeam(){
        $params = $this->request->param();
        $rule = [
            ['page', 'require', '页码不能为空'],
            ['pageSize', 'require', '每页查询条数不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $where = [
            'pid' => $this->distribution_user->id,
            'deletetime' => null,
        ];
        $list = OperateDistributionUser::where($where)
            ->limit(($params['page'] - 1) * $params['pageSize'], $params['pageSize'])
            ->order('id desc')
            ->field('id,full_name,mobile,avatar')
            ->select();
        $num = OperateDistributionUser::where($where)->count();
        if ($num > $params['page'] * $params['pageSize']) {
            $nextpage = true;
        } else {
            $nextpage = false;
        }
        $this->success('获取成功', ['list' => $list, 'nextpage' => $nextpage]);
    }

    /**
     * 收益明细
     */
    public function profitList(){
        $params = $this->request->param();
        $rule = [
            ['page', 'require', '页码不能为空'],
            ['pageSize', 'require', '每页查询条数不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $where = [
            'distribution_user_id' => $this->distribution_user->id,
            'deletetime' => null,
        ];
        if ($params['strtime'] != null){
            $todayTime =  strtotime($params['strtime'] . "00:00:00") . ',' . strtotime($params['strtime'] . "23:59:59");
            $where['addtotime'] = ['between',$todayTime];
        }
        $list = OperateDistributionProfit::where($where)
            ->limit(($params['page'] - 1) * $params['pageSize'], $params['pageSize'])
            ->order('id desc')
            ->field('*')
            ->select();
        $num = OperateDistributionProfit::where($where)->count();
        if ($num > $params['page'] * $params['pageSize']) {
            $nextpage = true;
        } else {
            $nextpage = false;
        }
        $this->success('获取成功', ['list' => $list, 'nextpage' => $nextpage]);
    }


    /**
     * 余额变动明细
     */
    public function moneylogList(){
        $params = $this->request->param();
        $rule = [
            ['page', 'require', '页码不能为空'],
            ['pageSize', 'require', '每页查询条数不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $where = [
            'distribution_user_id' => $this->distribution_user->id,
        ];
        $list = OperateDistributionMoneylog::where($where)
            ->limit(($params['page'] - 1) * $params['pageSize'], $params['pageSize'])
            ->order('id desc')
            ->field('*')
            ->select();
        $num = OperateDistributionMoneylog::where($where)->count();
        if ($num > $params['page'] * $params['pageSize']) {
            $nextpage = true;
        } else {
            $nextpage = false;
        }
        $this->success('获取成功', ['list' => $list, 'nextpage' => $nextpage]);
    }

    /**
     * 发起提现
     */
    public function withdrawalInitiate(){
        $param = $this->request->param();
        $rule = [
            ['money', 'require|>:0', '提现金额不能为空|提现金额必须是大于0的数字'],
            ['payment_mode', 'require', '提现方式不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        if($param['payment_mode'] == OperateDistributionMoneyWithdrawal::PAYMENT_MODE_XIANXIA){//打款方式为线下打款
            if (!array_key_exists('bank_number',$param) || !$param['bank_number'] ||
                !array_key_exists('bank_opening',$param) || !$param['bank_opening'] ||
                !array_key_exists('bank_account',$param) ||!$param['bank_account']){
                throw new Exception('银行卡信息不完善');
                return false;
            }
        }elseif ($param['payment_mode']  == OperateDistributionMoneyWithdrawal::PAYMENT_MODE_WEIXINSHOUKUANMA){//提现方式:4=微信收款码收款
            if (!array_key_exists('wechat_code_image',$param) ||!$param['wechat_code_image']){
                throw new Exception('微信收款码不能为空');
                return false;
            }
        }elseif ($param['payment_mode']  == OperateDistributionMoneyWithdrawal::PAYMENT_MODE_ZHIFUBAOSHOUKUANMA){//提现方式:5=支付宝收款码收款
            if (!array_key_exists('alipay_code_image',$param) ||!$param['alipay_code_image']){
                throw new Exception('支付宝收款吗不能为空');
                return false;
            }
        }
        $distribution_config = OperateDistributionConfig::where(['id' => 1])->field('wit_servicecharge,wit_minimun')->find();
        if($param['money'] < $distribution_config['wit_minimun']){
            $this->error("体现金额不得小于:{$distribution_config['wit_minimun']}元");
        }
        Db::startTrans();
        try {
            $distribution_user = OperateDistributionUser::where(['id' => $this->distribution_user->id])->find();//->lock(true)
            if($distribution_user->money < $param['money']){
                throw new Exception('余额不足');
            }
            $service_charge = number_format(( $param['money'] / 100 ) * $distribution_config['wit_servicecharge'],2,'.','') ;//手续费
            $actual_payment = $param['money'] - $service_charge;//实际需要打款金额
            $increase = [
                'distribution_user_id' => $distribution_user['id'],
                'money' => $param['money'],
                'witserpro' => $distribution_config['wit_servicecharge'],
                'service_charge' => $service_charge,
                'actual_payment' => $actual_payment,
                'payment_mode' => $param['payment_mode'],
                'explain' => $param['explain'],
                'status' => OperateDistributionMoneyWithdrawal::STATUS_DAICHULI,
                'applytime' => time(),
                'createtime' => time(),
                'bank_number' => $param['bank_number'],
                'bank_opening' => $param['bank_opening'],
                'bank_account' => $param['bank_account'],
                'wechat_code_image' => $param['wechat_code_image'],
                'alipay_code_image' => $param['alipay_code_image'],

            ];
            $withdrawal = OperateDistributionMoneyWithdrawal::create($increase);
            /**
             * 处理余额变动
             * @param int $agent_id 代理商ID
             * @param int $money 变动金额
             * @param  int $type 变动类型
             * @param array $data 数据
             */
            OperateDistributionMoneylog::moneyChange($distribution_user['id'],$param['money'],OperateDistributionMoneylog::TYPE_TIXIAN,[
                'memo' => '分销员申请提现',
                'withdrawal_id' => $withdrawal->id,
            ]);

            //更新收款信息
            $distribution_user->bank_number = $param['bank_number'] == "" ? $distribution_user->bank_number : $param['bank_number'];
            $distribution_user->bank_opening = $param['bank_opening'] == "" ? $distribution_user->bank_opening : $param['bank_opening'];
            $distribution_user->bank_account = $param['bank_account'] == "" ? $distribution_user->bank_account : $param['bank_account'];
            $distribution_user->wechat_code_image = $param['wechat_code_image'] == "" ? $distribution_user->wechat_code_image : $param['wechat_code_image'];
            $distribution_user->alipay_code_image = $param['alipay_code_image'] == "" ? $distribution_user->alipay_code_image : $param['alipay_code_image'];
            $distribution_user->save();

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('申请提现成功');
    }

    /**
     * 提现明细
     */
    public function withdrawalLog(){
        $params = $this->request->param();
        $rule = [
            ['page', 'require', '页码不能为空'],
            ['pageSize', 'require', '每页查询条数不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }

        $where = [
            'distribution_user_id' => $this->distribution_user->id,
        ];

        $list = OperateDistributionMoneyWithdrawal::where($where)
            ->limit(($params['page'] - 1) * $params['pageSize'], $params['pageSize'])
            ->order('id desc')
            ->field('*')
            ->select();
        foreach($list as $k => $v){

        }
        $num = OperateDistributionMoneyWithdrawal::where($where)->count();
        if ($num > $params['page'] * $params['pageSize']) {
            $nextpage = true;
        } else {
            $nextpage = false;
        }
        $this->success('获取成功', ['list' => $list, 'nextpage' => $nextpage]);
    }


    /**
     * 收款信息完善
    */
    public function collectionInformationUpdate(){
        $params = $this->request->param();
        $this->distribution_user->bank_number = $params['bank_number'];
        $this->distribution_user->bank_opening = $params['bank_opening'];
        $this->distribution_user->bank_account = $params['bank_account'];
        $this->distribution_user->wechat_code_image = $params['wechat_code_image'];
        $this->distribution_user->alipay_code_image = $params['alipay_code_image'];
        $this->distribution_user->save();
        $this->success('修改成功');
    }



    /**
     * 测试方法 ： 一些内部调用方法在这里测试
    */
    public function test(){
        //收益分成记录生成
        //OperateDistributionProfit::establishProfit(19,160,1);

        //收益分成发放到分销员余额
//        Db::startTrans();
//        try {
//            OperateDistributionProfit::grantProfit(4);
//            Db::commit();
//        } catch (Exception $e) {
//            Db::rollback();
//            $this->error($e->getMessage());
//        }
    }

}
